package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.enmu.LogOperationType;
import com.jinzhi.common.enmu.LogSysModule;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.common.vo.LogDownLoadVo;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzweb.service.JazSysUserService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.IpAddressUtil;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazOrderLogDao;
import com.jinzhi.jzweb.domain.JazOrderLogDO;
import com.jinzhi.jzweb.service.JazOrderLogService;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 
 * <pre>
 * 订单日志表
 * </pre>
 * <small> 2024-07-29 08:50:29 | Long</small>
 */
@Service
public class JazOrderLogServiceImpl extends CoreServiceImpl<JazOrderLogDao, JazOrderLogDO> implements JazOrderLogService {

    @Autowired
    private RoleService roleService;
    @Autowired
    private JazSysUserService jazSysUserService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private  JazOrderLogDao jazOrderLogDao;

    private static final String prefix="RZ10";
    /**
     * 获取日志编号
     *
     * @return
     */
    @Override
    public String getLogNo() {
        return baseMapper.getLogNo();
    }
    @Override
    @Transactional
    public void saveOrderLog(JazOrderLogDO jazOrderLogDO, UserDO user, HttpServletRequest request) {
        if (user==null){
            jazOrderLogDO.setUserId(-1L);
            jazOrderLogDO.setUsername("游客");
        }else {
            Long id = user.getId();
            jazOrderLogDO.setUserId(id);
            jazOrderLogDO.setUsername(user.getUsername());
            List<Long> listRoleId = userRoleService.listRoleId(id);
            // 查询角色
            StringBuffer buffer = new StringBuffer();
            StringBuffer buffer1 = new StringBuffer();
            if (listRoleId.size() > 0) {
                for (int i = 0; i < listRoleId.size(); i++) {
                    if (listRoleId.size()==1) {
                        jazOrderLogDO.setRoleId(String.valueOf(listRoleId.get(i)));
                    }else {
                        buffer.append(listRoleId.get(i)).append(",");
                        jazOrderLogDO.setRoleId(buffer.toString());
                    }
                }
                List<String> selroleNameList = userRoleService.selroleNameList(id);
                for (int i = 0; i < selroleNameList.size(); i++) {
                    if (selroleNameList.size()==1) {
                        jazOrderLogDO.setRoleName(selroleNameList.get(i));
                    }else {
                        buffer1.append(selroleNameList.get(i)).append(",");
                        jazOrderLogDO.setRoleName(buffer.toString());
                    }
                }
            }
        }

        //获取公网ip
        String outIP = getRealClientIP(request);
        //根据request获取地址
        String realClientAddress = getRealClientAddress(request);

//        String ipAddressByOnline = IpAddressUtil.getIpAddressByOnline(outIP);
        jazOrderLogDO.setIp(outIP);
        jazOrderLogDO.setAddress(realClientAddress);
        jazOrderLogDO.setCreateTime(new Date());
        // 获取日志编号
        String logNo = getLogNo();
        if (StringUtil.notEmpty(logNo)) {
            Integer substring = Integer.parseInt(logNo.substring(3));
            jazOrderLogDO.setCode(prefix+(substring+1));
        }else {
            jazOrderLogDO.setCode(prefix+1);
        }
        // 保存系统日志
        try {
            jazOrderLogDao.insert(jazOrderLogDO);
        } catch (Exception e) {
            log.error("日志表插入失败，{}", e);
            throw new RuntimeException(e);
        }
    }
    // 获取客户端真实IP地址的辅助方法
    private String getRealClientIP(HttpServletRequest request) {
        String ip = request.getHeader("Ip");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }
    private String getRealClientAddress(HttpServletRequest request) {
        String address = request.getHeader("Addres");
        if (address == null || address.length() == 0 || "unknown".equalsIgnoreCase(address)) {
            address = "";
        }
        try {
            address = URLDecoder.decode(address, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println("IP地址获取失败");
        }
        return address;
    }



    @Override
    public Result<Page<JazOrderLogDO>> selOrderLogList(JazOrderLogDO jazOrderLogDO) {
        Page<JazOrderLogDO> page = new Page<>(jazOrderLogDO.getCurrent(), jazOrderLogDO.getSize());
        List<JazOrderLogDO> voList = new ArrayList<>();
        Wrapper<JazOrderLogDO> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(jazOrderLogDO.getUsername())){
            wrapper.like("username","%"+jazOrderLogDO.getUsername()+"%");
        }
        if (StringUtils.isNotBlank(jazOrderLogDO.getStartTime()) && StringUtils.isNotBlank(jazOrderLogDO.getEndTime())) {
            wrapper.between("create_time", jazOrderLogDO.getStartTime(), jazOrderLogDO.getEndTime());
        }
        if (jazOrderLogDO.getType()!=null&& !jazOrderLogDO.getType().equals(-1)){
            wrapper.eq("type", jazOrderLogDO.getType());
        }
        if (jazOrderLogDO.getSystemModules()!=null&& !jazOrderLogDO.getSystemModules().equals(-1)){
            wrapper.eq("system_modules", jazOrderLogDO.getSystemModules());
        }
        if (jazOrderLogDO.getStatus()!=null&& !jazOrderLogDO.getStatus().equals(-1)){
            wrapper.eq("status", jazOrderLogDO.getStatus());
        }
        if (jazOrderLogDO.getIds() != null && jazOrderLogDO.getIds().size()>0) {
            wrapper.in("id",jazOrderLogDO.getIds());
        }
        wrapper.orderBy("id",false);
        Page<JazOrderLogDO> jazOrderLogDOPage = this.selectPage(page, wrapper);
        return Result.ok(jazOrderLogDOPage);
    }

    /**
     * 日志导出
     *
     * @param response
     * @param logDTO
     */
    @Override
    public void downloadImportTemplate(HttpServletResponse response, JazOrderLogDO logDTO) {
        List<LogDownLoadVo> list1 = new LinkedList<>();
        List<JazOrderLogDO> list = this.selOrderLogList(logDTO).getData().getRecords();
        for(JazOrderLogDO li:list){
            LogDownLoadVo logDownLoadVo=new LogDownLoadVo();
            BeanUtils.copyProperties(li,logDownLoadVo);
            logDownLoadVo.setLogNo(li.getCode());
            logDownLoadVo.setOperationAddress(li.getAddress());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 使用format()方法将Date转换为字符串
            String formattedDate = sdf.format(li.getCreateTime());
            logDownLoadVo.setGmtCreate(formattedDate);
            // 日志状态
            if (li.getStatus()!=null){
                if (li.getStatus() == 0){
                    logDownLoadVo.setStatus("成功");
                } else if (li.getStatus() == 1) {
                    logDownLoadVo.setStatus("失败");
                }
            } else {
                logDownLoadVo.setStatus(null);
            }
            // 系统模块
            if (li.getSystemModules()!=null){
                switch (li.getSystemModules()) {
                    case 101: logDownLoadVo.setSysModule(LogSysModule.ORDER_LIST.getName()); break;
                    case 102: logDownLoadVo.setSysModule(LogSysModule.ORDER_ACTIVITY.getName()); break;
                    case 103: logDownLoadVo.setSysModule(LogSysModule.ORDER_COURSES.getName()); break;
                    case 104: logDownLoadVo.setSysModule(LogSysModule.ORDER_USER_ORDER.getName()); break;
                    case 105: logDownLoadVo.setSysModule(LogSysModule.ORDER_MANAGEMENT1.getName()); break;
                    default: logDownLoadVo.setSysModule("未知"); break;
                }
            }else {
                logDownLoadVo.setSysModule(null);
            }
            // 操作类型
            if (li.getType()!=null){
                switch (li.getType()) {
                    case 1: logDownLoadVo.setOperationType(LogOperationType.ADD.getName()); break;
                    case 2: logDownLoadVo.setOperationType(LogOperationType.DELETE.getName()); break;
                    case 3: logDownLoadVo.setOperationType(LogOperationType.EDIT.getName()); break;
                    case 4: logDownLoadVo.setOperationType(LogOperationType.EXPORT.getName()); break;
                    case 5: logDownLoadVo.setOperationType(LogOperationType.IMPORT.getName()); break;
                    case 6: logDownLoadVo.setOperationType(LogOperationType.TRANSFER.getName()); break;
                    case 7: logDownLoadVo.setOperationType(LogOperationType.TRANSFER1.getName()); break;
                    case 8: logDownLoadVo.setOperationType(LogOperationType.TRANSFER2.getName()); break;
                }
            }else {
                logDownLoadVo.setOperationType(null);
            }
            list1.add(logDownLoadVo);
        }
        //导出操作
        EasyPoiUtil.exportExcel(list1, "订单日志导出", "订单日志导出", LogDownLoadVo.class, "订单日志导出", response);
    }
}
